import fs from 'fs';
import path from 'path';
import plugin from '../../lib/plugins/plugin.js';
import cfg from '../../lib/config/config.js';
import common from '../../lib/common/common.js';
import fetch from 'node-fetch';
import moment from "moment"
//首发@老颜-3400664096
//该插件支持V3喵崽和原版,请将本插件放入bot根目录/plugins/example中

/*
更新日志
v1.0 更新 添加指定文件夹黑名单
v2.0 更新 修复拉黑功能无法被踢人问题
v3.0 更新 主人判断但主人可用，在更新了踢出之后的提示
v4.0 更新 白名单系统，有添加白名单，删除白名单，白名单列表，有白名单的将不能被拉黑名单
v5.0 更新 修复部分bug，添加清空黑名单和清空白名单功能，在添加了帮助系统用于便捷查询指定功能
v5.2 更新 白名单但超级主人可用，可以自定义QQ号在193和217更改
*/

const type = 1; // 根据你的需求来定义 type 的值
export class Blacklist extends plugin {
    constructor() {
        const currentFilePath = new URL(import.meta.url).pathname;
        const currentFolderPath = path.dirname(currentFilePath);
        const blacklistFolderPath = path.join(currentFolderPath, 'blacklist');
        const whitelistFolderPath = path.join(currentFolderPath, 'whitelist');

        super({
            name: '全局拉黑',
            dsc: '全局拉黑',
            event: 'message',
            priority: 2520,
            rule: [
                {
                    reg: `#?(黑名|黑名单)帮助`,
			    	fnc: 'HmobyHelp'
				},
				{
                    reg: '^#?加黑名单 (\\d+)$',
                    fnc: 'addBlacklist',
                },
                {
                    reg: '^#?删黑名单 (\\d+)$',
                    fnc: 'removeBlacklist',
                },
                {
                    reg: '^#?黑名单列表$',
                    fnc: 'listBlacklist',
                },
                {
                    reg: '^#?清空黑名单$',
                    fnc: 'clearBlacklist',
                },
                {
                    reg: '^#?加白名单 (\\d+)$',
                    fnc: 'addWhitelist',
                },
                {
                    reg: '^#?删白名单 (\\d+)$',
                    fnc: 'removeWhitelist',
                },
                {
                    reg: '^#?白名单列表$',
                    fnc: 'listWhitelist',
                },
                {
                    reg: '^#?清空白名单$',
                    fnc: 'clearWhitelist',
                },
                {
                    reg: '.*',
                    fnc: 'checkBlacklist',
                },
            ],
        });

        this.blacklistFolderPath = blacklistFolderPath;
        this.whitelistFolderPath = whitelistFolderPath;
        this.blacklist = new Set();
        this.whitelist = new Set();

        this.loadBlacklist();
        this.loadWhitelist();
    }

    loadBlacklist() {
        try {
            if (!fs.existsSync(this.blacklistFolderPath)) {
                fs.mkdirSync(this.blacklistFolderPath);
            }

            const files = fs.readdirSync(this.blacklistFolderPath);
            files.forEach((file) => {
                const qqNumber = file.replace('.txt', '');
                this.blacklist.add(qqNumber);
            });
        } catch (error) {
            console.error('无法读取黑名单文件夹。');
        }
    }

    loadWhitelist() {
        try {
            if (!fs.existsSync(this.whitelistFolderPath)) {
                fs.mkdirSync(this.whitelistFolderPath);
            }

            const files = fs.readdirSync(this.whitelistFolderPath);
            files.forEach((file) => {
                const qqNumber = file.replace('.txt', '');
                this.whitelist.add(qqNumber);
            });
        } catch (error) {
            console.error('无法读取白名单文件夹。');
        }
    }

    async HmobyHelp (e) {
		let ver = '5.0'
		if(type <= 3 && type >= 1) {
			ver = '5.0'
		}
		let versioninfo = `当前黑名单插件版本：${ver}`
		let msg = `使用方法：\n#加黑名单+QQ号\n#删黑名单+QQ号\n#黑名单列表\n#加白名单+QQ号\n#删白名单+QQ号\n#白名单列表\n#清空黑名单\n#清空白名单`
		let msglist = await common.makeForwardMsg(e, [msg, versioninfo], `黑名单帮助`)
		e.reply(msglist);
		return true;
	}
    async addBlacklist(e) {
        if (!e.isMaster && !e.member.is_admin) {
            e.reply('暂无权限，但限主人可用');
            return true;
        }
        const command = e.raw_message;
        const regex = /^#?加黑名单 (\d+)$/;
        const match = command.match(regex);
        const qqNumber = match?.[1];

        if (!qqNumber) {
            e.reply('请输入要添加到黑名单的 QQ 号');
            return false;
        }

        if (this.whitelist.has(qqNumber)) {
            e.reply(`QQ 号 ${qqNumber} 已在白名单中，无法添加到黑名单`);
            return true;
        }

        this.blacklist.add(qqNumber);
        const fileName = `${qqNumber}.txt`;
        fs.writeFileSync(path.join(this.blacklistFolderPath, fileName), '');

        e.reply(`已将 QQ 号 ${qqNumber} 添加到黑名单`);
        return true;
    }

    async removeBlacklist(e) {
        if (!e.isMaster && !e.member.is_admin) {
            e.reply('暂无权限，但限主人可用');
            return true;
        }
        const command = e.raw_message;
        const regex = /^#?删黑名单 (\d+)$/;
        const match = command.match(regex);
        const qqNumber = match?.[1];

        if (!qqNumber) {
            e.reply('请输入要移除黑名单的 QQ 号');
            return false;
        }

        this.blacklist.delete(qqNumber);
        const fileName = `${qqNumber}.txt`;
        fs.unlinkSync(path.join(this.blacklistFolderPath, fileName));

        e.reply(`已将 QQ 号 ${qqNumber} 从黑名单移除`);
        return true;
    }

    async listBlacklist(e) {
        const blacklist = Array.from(this.blacklist);
        if (blacklist.length === 0) {
            e.reply('黑名单为空');
        } else {
            e.reply(`黑名单：\n${blacklist.join('\n')}`);
        }

        return true;
    }

    async addWhitelist(e) {
        const masterQQ = '3400664096'; // 指定主人QQ号
         if (e.sender.user_id != masterQQ) {
          e.reply('暂无权限，仅限超级主人可用');
           return true;
          }
        const command = e.raw_message;
        const regex = /^#?加白名单 (\d+)$/;
        const match = command.match(regex);
        const qqNumber = match?.[1];

        if (!qqNumber) {
            e.reply('请输入要添加到白名单的 QQ 号');
            return false;
        }

        this.whitelist.add(qqNumber);
        const fileName = `${qqNumber}.txt`;
        fs.writeFileSync(path.join(this.whitelistFolderPath, fileName), '');

        e.reply(`已将 QQ 号 ${qqNumber} 添加到白名单`);
        return true;
    }

    async removeWhitelist(e) {
        const masterQQ = '3400664096'; // 指定主人QQ号
         if (e.sender.user_id != masterQQ) {
          e.reply('暂无权限，仅限超级主人可用');
           return true;
          }
        const command = e.raw_message;
        const regex = /^#?删白名单 (\d+)$/;
        const match = command.match(regex);
        const qqNumber = match?.[1];

        if (!qqNumber) {
            e.reply('请输入要移除白名单的 QQ 号');
            return false;
        }

        this.whitelist.delete(qqNumber);
        const fileName = `${qqNumber}.txt`;
        fs.unlinkSync(path.join(this.whitelistFolderPath, fileName));

        e.reply(`已将 QQ 号 ${qqNumber} 从白名单移除`);
        return true;
    }

    async listWhitelist(e) {
        const whitelist = Array.from(this.whitelist);
        if (whitelist.length === 0) {
            e.reply('白名单为空');
        } else {
            e.reply(`白名单：\n${whitelist.join('\n')}`);
        }

        return true;
    }
    async clearBlacklist(e) {
        if (!e.isMaster && !e.member.is_admin) {
            e.reply('暂无权限，但限主人可用');
            return true;
        }
        try {
            const files = fs.readdirSync(this.blacklistFolderPath);
            files.forEach((file) => {
                fs.unlinkSync(path.join(this.blacklistFolderPath, file));
            });
            this.blacklist.clear();

            e.reply('已清空黑名单');
            return true;
        } catch (error) {
            console.error('清空黑名单时出错:', error);
            e.reply('清空黑名单时出错');
            return false;
        }
    }
    
    async clearWhitelist(e) {
     const masterQQ = '3400664096'; // 指定主人QQ号
      if (e.sender.user_id != masterQQ) {
        e.reply('暂无权限，仅限超级主人可用');
          return true;
         }
        try {
            const files = fs.readdirSync(this.whitelistFolderPath);
            files.forEach((file) => {
                fs.unlinkSync(path.join(this.whitelistFolderPath, file));
            });
            this.whitelist.clear();

            e.reply('已清空白名单');
            return true;
        } catch (error) {
            console.error('清空白名单时出错:', error);
            e.reply('清空白名单时出错');
            return false;
        }
    }
    
    async checkBlacklist(e) {
        try {
            if (!fs.existsSync(this.blacklistFolderPath)) {
                fs.mkdirSync(this.blacklistFolderPath);
            }

            if (!fs.existsSync(this.whitelistFolderPath)) {
                fs.mkdirSync(this.whitelistFolderPath);
            }

            const qqNumber = e.sender.user_id.toString();
            if (this.blacklist.has(qqNumber) && !this.whitelist.has(qqNumber)) {
                const member = e.member;
                await member.kick();
                await e.reply(`QQ 号 ${qqNumber} 是黑名单已踢出群聊`);
                return false;
            }

            return true;
        } catch (error) {
            console.error('无法读取名单文件夹。');
            return true;
        }
    }
}
